<?php 

namespace App\Repositories;
use App\Repositories\CustomerRepository;
use App\Repositories\OrderRepository;
use Illuminate\Support\Collection;

class RenewRepository extends Repository 
{
    public function model() 
    {
        return 'App\Models\Renew';
    }

    public function paginateList($where = [], $page = 20)
    {
        $model = $this->model->with('order');
        $where = $where->filter(function ($value) { return $value; });

        if ($where->has('word')) {

	        $customer = app(CustomerRepository::class);
	        $order = app(OrderRepository::class);

	        $customerIds = $customer->findIdsByname($where->get('word'));
	        $orderIds = $order->getIdsByCustomer($customerIds);

	        $model = $model->whereIn('order_id', $orderIds);
        }

        return $model->paginate($page);
    }

    public function getLists(Collection $orderIds)
    {
        return $this->model->whereIn('order_id', $orderIds)->get();
    }

    /**
     * 批量更新客户所属的续费的业务员
     *
     * @param  int|array $ids 客户信息ID
     * @param  int  $saler  业务员ID
     * @return Response
     */
    // 
    public function updateSaler($cid, $salerId)
    {
        if (!$cid) {
            return false;
        }

        $order = app(OrderRepository::class);
        $orderIds = $order->getIdsByCustomer($cid);

        if ($orderIds) {
            return $this->model->whereIn('order_id', $orderIds)->update(['saler_id'=>$salerId]);
        }
    }

    // 根据用户得到续费的订单数量
    public function getCountsByUser($id)
    {
        return $this->model->where('saler_id', $id)->count();
    }
}